const cors = require('@koa/cors');
const bodyParser = require('koa-bodyparser');
const serve = require('koa-static');
const config = require('../config');

// CORS中间件
const corsMiddleware = cors({
  origin: function (ctx) {
    const allowedOrigins = config.cors.allowedOrigins;
    
    // 如果配置为 '*'，允许所有来源
    if (allowedOrigins === '*') {
      return ctx.request.header.origin || '*';
    }
    
    // 如果配置为数组，检查特定来源列表
    const requestOrigin = ctx.request.header.origin;
    if (allowedOrigins.includes(requestOrigin)) {
      return requestOrigin;
    }
    return allowedOrigins[0]; // 默认值
  },
  credentials: config.cors.credentials,
  allowMethods: config.cors.allowMethods,
  allowHeaders: config.cors.allowHeaders
});

// 错误处理中间件
const errorHandler = async (ctx, next) => {
  try {
    await next();
  } catch (err) {
    ctx.status = err.status || 500;
    ctx.body = {
      success: false,
      message: err.message || '服务器内部错误'
    };
    console.error('Error:', err);
  }
};

// 静态文件服务中间件
const staticServe = serve(config.storage.path);

module.exports = {
  corsMiddleware,
  errorHandler,
  bodyParser: bodyParser(),
  staticServe
}; 